/*
** get_next_line.c for gnl in /home/nadali_t//local/Projets/CprgElem/bsq/get_next_line
** 
** Made by thomas nadalie
** Login   <nadali_t@epitech.net>
** 
** Started on  Mon Dec  5 15:28:05 2011 thomas nadalie
** Last update Mon Dec  5 15:28:14 2011 thomas nadalie
*/

#include	<unistd.h>
#include	<stdlib.h>
#include	"get_next_line.h"

void		*xmalloc(int n)
{
  void		*ret;

  ret = malloc(n);
  if (!ret)
    exit(1);
  return (ret);
}

char		*to_return(t_get *t, t_var *v)
{
  if (t->buff[t->count] == '\n')
    {
      t->count++;
      v->out[v->cpt] = '\0';
      return (v->out);
    }
  if (t->count == t->nb_read)
    t->count = 0;
  return (0);
}

void		init_var(t_var *v)
{
  v->cpt = 0;
  v->out = xmalloc(BUFF_SIZE * sizeof(*v->out));
  v->out[0] = 0;
}

char		*get_next_line(const int fd)
{
  static t_get	t;
  t_var		v;

  init_var(&v);
  while (v.cpt < BUFF_SIZE)
    {
      if (t.count == 0)
	if ((t.nb_read = read(fd, t.buff, READ_SIZE)) <= 0)
	  {
	    if (v.out[v.cpt] != 0)
	      {
		v.out[v.cpt] = '\0';
		return (v.out);
	      }
	    else
	      return (0);
	  }
      while ((t.buff[t.count] != '\n') && (v.cpt < BUFF_SIZE) &&
	     (t.count < t.nb_read))
	v.out[v.cpt++] = t.buff[t.count++];
      if (to_return(&t, &v))
	return (v.out);
    }
  return (v.out);
}
